package org.gd.helloconcurrent.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class SimpleExecutor {

    private static final int N_THREADS = 2;

    public static void main(String...a) {
        try {
            System.out.println(Thread.currentThread().getName() + " ===================================");
            ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
            List<Future<Integer>> list = new ArrayList<Future<Integer>>();
            SimpleCallable simpleCallable = new SimpleCallable();
            Future<Integer> simpleFuture = executor.submit(simpleCallable);
            for (int i = 0; i < 10; i++) {
                Future<Integer> submit = executor.submit(new SimpleCallable(simpleFuture));
                list.add(submit);
            }
            executor.shutdown();
            // Wait until all threads are finish

            while(true) {
                if(list.get(0).isDone()) {
                    System.out.println("done");
                    break;
                }
                Thread.sleep(10);
            }

            for(;!executor.isTerminated(););


            AtomicInteger sum  = new AtomicInteger(0);
            for(Future<Integer> future: list) {
                /*System.out.printf("isCancelled: %b; isDone: %b; get: %d; \n",
                        future.isCancelled(),
                        future.isDone(),
                        future.get());*/
                if(future.isDone()) {
                    sum.addAndGet(future.get());
                }
            }
            System.out.println("sum: " + sum);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace(System.err);
        } finally {
            System.out.println(Thread.currentThread().getName() + " ===================================");
        }
    }
}
